package com.lxlx.weixinlx.controller;

import com.lxlx.weixinlx.domain.Student;
import com.lxlx.weixinlx.service.ExcelService;
import com.lxlx.weixinlx.utils.CsvExportUtils;
import com.lxlx.weixinlx.utils.CvsExportUtils;
import com.lxlx.weixinlx.utils.ExportExcelUtils;
import com.lxlx.weixinlx.utils.ExportUtilCsv;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author liuhuan
 * @date
 * @描述
 */
@Controller
public class ExcelController {
    @Autowired
    private ExcelService excelService;

    @RequestMapping("/exporExcel")
    public void exporExcel(HttpServletResponse response, HttpServletRequest request){
        List<Student> students = excelService.student();
        try {
            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet sheet = workbook.createSheet("A表");
            String[] titles = {"id","姓名","生日","性别"};
            XSSFRow row = sheet.createRow(0);
            for (int i = 0; i < titles.length; i++) {
                XSSFCell cell = row.createCell(i);
                cell.setCellValue(titles[i]);
            }
            for (int i = 0; i < students.size(); i++) {
                row = sheet.createRow(i + 1);
                Student student = students.get(i);
                XSSFCell idCell = row.createCell(0);
                idCell.setCellValue(student.getId());
                XSSFCell nameCell = row.createCell(1);
                nameCell.setCellValue(student.getName());
                XSSFCell bCell = row.createCell(2);
                bCell.setCellValue(student.getBirth());
                XSSFCell sexCell = row.createCell(3);
                sexCell.setCellValue(student.getSex());

            }
            //文件名
            String fileName = "好好";
            //浏览器及乱码问题
            String agent = request.getHeader("USER-AGENT").toLowerCase();
            response.setContentType("application/vnd.ms-excel");
            String codedFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            if (agent.contains("firefox")) {
                response.setCharacterEncoding("utf-8");
                response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes(), "ISO8859-1") + ".xls" );
            } else {
                response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");
            }
            //写出
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 通用 导出
     * @param response
     * @param request
     */
    @RequestMapping("/exporExcelb")
    public void exporExcelb(HttpServletResponse response, HttpServletRequest request){
        List<Student> students = excelService.student();

        try {
            ExportExcelUtils<Student> excelUtils = new ExportExcelUtils<>();
            String[] titles = {"id","姓名","生日","性别"};
            Map<String, Object> params = new HashMap<>();
            params.put("objs",students);
            params.put("name","学生表aa");
            params.put("response",response);
            params.put("request",request);
            params.put("titles",titles);
            params.put("sheetName","表1");
            excelUtils.exportExcelb(params);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

      /**
     * 导出cvs格式,,,下载和保存
     * @param response
     * @param request
     */
    @RequestMapping("/exporExcelc")
    public void exporExcelc(HttpServletResponse response, HttpServletRequest request) throws IOException {
        List<Student> students = excelService.student();
        List<List<Object>> dataList = new ArrayList<List<Object>>();
        List<Object> rowList;
        for (int i = 0; i < students.size(); i++) {
            rowList = new ArrayList<Object>();
            Object[] row = new Object[4];
            row[0] = students.get(i).getId();
            row[1] = students.get(i).getName();
            row[2] = students.get(i).getBirth();
            row[3] = students.get(i).getSex();
            for(int j=0;j<row.length;j++){
                rowList.add(row[j]);
            }
            dataList.add(rowList);
        }

        CvsExportUtils cvsExportUtils = new CvsExportUtils();

        cvsExportUtils.exportCsv(response,request,dataList);


    }

    /**
     * 导出cvs格式 下载
     * @param response
     * @param request
     */
    @RequestMapping("/exporExceld")
    public void exporExceld(HttpServletResponse response, HttpServletRequest request) throws IOException {
        List<Student> logList = excelService.student();
        List<Map<String, Object>> dataList = null;

       // List<SysLog> logList = sysLogService.findAll();// 查询到要导出的信息

        if (logList.size() == 0) {
           // ResultUtil.failure("无数据导出");
        }
        String sTitle = "id,用户名,日期,性别";
        String fName = "日注册";
        String mapKey = "id,name,birth,sex";
        dataList = new ArrayList<>();
        Map<String, Object> map = null;
        for (Student order : logList) {
            map = new HashMap<>();
            map.put("id", order.getId());
            map.put("name", order.getName());
            map.put("birth",order.getBirth());
            map.put("sex", order.getSex());
            dataList.add(map);
        }

        try{
            OutputStream os = response.getOutputStream();
            /*ExportUtilCsv.responseSetProperties(fName, response,request);
            ExportUtilCsv.doExport(dataList, sTitle, mapKey, os);*/
            CsvExportUtils.responseSetProperties(fName, response,request);
            CsvExportUtils.doExport(dataList, sTitle, mapKey, os);
            os.close();
        } catch (Exception e) {
            System.out.println("生成csv文件失败");
            //log.error("生成csv文件失败", e);
        }
        System.out.println("生成csv文件成功");
    }









}
